<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<?php include 'logincheck.php'?>
<html>
<head>
<title>Alert subscribers</title>
<?php
include 'head.php';
?>
</head>
<body>
<?php
include 'nav.php';
?>
<div id="wrapper">
	<div id="content">
	<?php
	if(!isSet($_POST['idList']) || empty($_POST['idList'])){die('No item selected');};
	
	$idList = $_POST['idList'];
	include 'connect.php';
	
	mysql_select_db($db, $con);
	$query  = "SELECT ID, Name, URL, postBody FROM {$table} WHERE ID IN ({$idList})";
	$result = mysql_query($query) or die(mysql_error());
	
	$op = "";
	
	while($row = mysql_fetch_assoc($result)) {
		$id = $row['ID'];
		$name = $row['Name'];
		$url = "http://".$_SERVER['SERVER_NAME']."/".$row['URL']."_id_".$row['ID'];
		$postBody = $row['postBody'];
		preg_match_all('/^(\w).+[.?!:;]/m',stripslashes($postBody), $out);
		$op = $op."<h2><a href='{$url}'>".$name ."</a></h2><p>".$out[0][0]."<br />".$out[0][1]."<br />...<br /><a href='{$url}'>Read more &gt;&gt;</a></p>";
	}
	$op = $op."<hr /><small sytle='color:gray;'>You are receiving this mail because you are subscribed to CraftnTalk. To unsubscribe, please click <a href='http://craftntalk.com/unsubscribe'>here</a>.</small>";
	$query  = "SELECT email FROM subscribers WHERE isverified = true";
	$result = mysql_query($query) or die(mysql_error());
	
	$mailList = "";
	
	while($row = mysql_fetch_assoc($result)) {
		$mailList = $mailList.$row['email'].", ";
	}
	

	
////////send mail
$mail_subject    = "Craft and Talk : Newsletter"; 

$mail_message    = "<p>Hi,</p>"
					."<p>There have been new posts on CraftnTalk lately. I thought you might be interested.</p>"
					.$op;

$mail_headers    = "From: webmaster@".$_SERVER['SERVER_NAME'] . "\r\n". 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$mail_headers = $mail_headers."Bcc: ".$mailList."\r\n";

$mail_parameters = ""; 

ini_set('sendmail_from',"webmaster@".$_SERVER['SERVER_NAME']); 

$result = mail("",$mail_subject,$mail_message,$mail_headers,$mail_parameters); 
if ($result == 1) {
	$query  = "UPDATE {$table} SET isNotified = true WHERE ID IN ({$idList})";
	$result = mysql_query($query) or die(mysql_error('Unable to update the notification status, but mail sent.'));
	echo '<h1>Mail sent</h1><p>Mail sent to all subscribers</p>';
}
else {
	echo '<h2>Mail could not be sent. Try again later.</h2>';
}
	mysql_close($con);
?>
	</div>
</div>
<?php
include 'footer.php';
?>
</body>
</html>